/*  @typescript-eslint/explicit-module-boundary-types */
import { MessageEntity } from '@src/entities/sys/message.entity';
import { ObjectType } from '@src/types/obj-type';
import { TaskEntity } from '@src/entities/sys/task.entity';
import { BaseService } from '@src/service/base/base.service';
import { LoggerService } from '@src/service/admin/logger/logger.service';
import { Injectable, Logger } from '@nestjs/common';
import { Cron, Interval, Timeout, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WsResponse, SubscribeMessage, WebSocketServer } from '@nestjs/websockets';

@Injectable()
export class TasksService extends BaseService {
  constructor(
    private readonly loggerService: LoggerService,
    @InjectRepository(TaskEntity)
    private readonly taskRepository: Repository<TaskEntity>,
    private readonly scheduleRegistry: SchedulerRegistry,
    @InjectRepository(MessageEntity)
    private readonly messageRepository: Repository<MessageEntity>
  ) {
    super(taskRepository)
  }

  /** 
   * 创建定时任务
  */

  public async startTask(bodyOptions: ObjectType): Promise<WsResponse<any>> {
    const { name, rules } = bodyOptions;
    const callback = () => {
      Logger.warn(`Interval ${name} executing at time (${rules})!`);
      return { event: 'events', data: `Interval ${name} executing at time (${rules})!` }
    };
    const interval = setInterval(callback, parseInt(rules));
    const msg = await this.messageRepository.create({ origin: '测试', title: '测试', subtitle: '测试', content: '测试' })
    await this.messageRepository.save(msg);

    this.scheduleRegistry.addInterval(name, interval);
    return callback()
  }

  /** 
   * 暂停定时任务
  */
  public async stopTask(bodyOptions: ObjectType): Promise<any> {
    const { name } = bodyOptions;
    return this.scheduleRegistry.deleteInterval(name);
  }
}